package com.thd.springboottest.shironostate.filter;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.Set;

/**
 * 如：roles[admin,user],这样配置的时候需要同时是admin和user角色是才能通过。
 * 该过滤器可以实现 任意有一个角色即可通过
 */
public class RoleOrFilter extends RolesAuthorizationFilter {
    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
        Subject subject = this.getSubject(request, response);
        String[] rolesArray = (String[])mappedValue;
        if (rolesArray == null && rolesArray.length == 0) {
            return true;
        }
        Set<String> roles = CollectionUtils.asSet(rolesArray);
        if(roles == null || roles.size() ==0) {
            return true;
        }
        for(String r : roles){
            if(subject.hasRole(r)){
                return true;
            }
        }

        return false;

    }
}
